import configparser
import multiprocessing
import os
import json
import time
from datetime import datetime, timezone
from urllib.parse import urlencode

from PyQt6.QtCore import Qt, QMimeData, pyqtSignal, QMetaObject
from PyQt6.QtWidgets import QDialog, QMessageBox, QInputDialog
from PyQt6.QtGui import QDragEnterEvent, QDropEvent

import Global
import threading
import queue

from Comm.ProxyUtil import ProxyUtil
from HTTP.HttpUtil import HttpUtil
from Script.GameFun import GameFun


from UI.BindAccount import Ui_Dialog_BindAccount


class BindAccount(QDialog, Ui_Dialog_BindAccount):
    # 添加信号用于在主线程中显示对话框
    show_message_box_signal = pyqtSignal(str, str, str)
    
    def __init__(self):
        super().__init__()
        # 设置UI
        self.setupUi(self)
        self.bind_thread=None
        
        # 连接信号到槽函数
        self.show_message_box_signal.connect(self.show_message_box_in_main_thread)
        
        # 添加一个事件标志，用于线程间同步
        self.dialog_response = None
        self.dialog_event = threading.Event()

        # self.edit_guestAccount.setText("272742890632")
        # self.edit_token.setText("17GPTIW4YaQj3jGX6MPEzNPvogc4oahsvxaHEuwzLIFZlr/VArLgYqCzhqDP7+Zr7pM=")
        # self.edit_UUID.setText("a9d4db97-3dbf-4a51-9319-dae554734e85")
        # self.edit_email.setText("fpk491@rerollbox.com")
        # self.edit_emailpass.setText("bsx896")

        # 连接信号槽
        self.btn_bindAccount.clicked.connect(self.on_bind_account)
        self.btn_clear.clicked.connect(self.on_clear_fields)
        self.pushButton_StopBind.clicked.connect(self.on_stopBind)
        self.edit_Getmail_adress.textChanged.connect(self.on_Getmail_adress_changed)
        self.edit_proxyIP.textChanged.connect(self.on_proxyIP_changed)
        # 启用拖放功能
        self.setAcceptDrops(True)

        # 初始化日志
        #self.log("请拖拽.ini文件到窗口或手动填写账号信息")
        self.log("""
        代理支持的格式：
            - SOCKET5带密码 socket5://账号:密码@IP地址:端口
            - SOCKET5无密码 socket5://IP地址:端口
            - HTTP带密码 http://账号:密码@IP地址:端口
            - HTTP无密码 http://IP地址:端口
            - HTTPS带密码 https://账号:密码@IP地址:端口
            - HTTPS无密码 https://IP地址:端口""")
        self.bind_queue = queue.Queue()
        self.timer = self.startTimer(100)  # 每100ms检查队列
        self.pushButton_StopBind.setEnabled(False)

        self.account =''
        self.username=''
        self.proxy={}
        Getmail_adress =Global.read_ini(Global.ConfigFileName, 'Bind', 'mail_adress', 'https://mail.rerollbox.com/api/getcode.php?yhm={mail}&mm={pass}')
        self.edit_Getmail_adress.setText(Getmail_adress)
        proxyIP = Global.read_ini(Global.ConfigFileName, 'Bind', 'proxyIP','')
        self.edit_proxyIP.setText(proxyIP)
    def on_Getmail_adress_changed(self):
        Getmail_adress = self.edit_Getmail_adress.text()
        Global.write_ini(Global.ConfigFileName, 'Bind', 'mail_adress', Getmail_adress)
    def on_proxyIP_changed(self):
        proxyIP = self.edit_proxyIP.text()
        Global.write_ini(Global.ConfigFileName, 'Bind', 'proxyIP', proxyIP)
    def dragEnterEvent(self, event: QDragEnterEvent):
        # 检查拖拽的数据是否包含URL（文件路径）
        if event.mimeData().hasUrls():
            # 获取文件路径
            file_path = event.mimeData().urls()[0].toLocalFile()
            # 检查是否是.ini文件
            if file_path.endswith('.ini'):
                event.acceptProposedAction()
                return
        # 如果不是.ini文件，拒绝拖拽
        event.ignore()
    
    def dropEvent(self, event: QDropEvent):
        # 获取拖拽的文件路径
        file_path = event.mimeData().urls()[0].toLocalFile()
        self.log(f"接收到文件: {file_path}")
        
        # 解析.ini文件
        self.parse_ini_file(file_path)
        
        # 接受拖拽操作
        event.acceptProposedAction()
    
    def parse_ini_file(self, file_path):
        try:
            account = Global.read_ini(file_path, "System", "userid", "")
            token =Global.read_ini(file_path,"System","token","")
            if not account:
                filename = os.path.basename(file_path)  # 获取文件名 '649944568504640376.ini'
                account = filename.split('.')[0]
                account = account.split('_')[0]
            self.edit_guestAccount.setText(account)
            self.edit_token.setText(token)

        except Exception as e:
            self.log(f"解析文件时出错: {str(e)}")

    def show_dialog(self):
        # 在主线程中弹出输入框
        text, ok = QInputDialog.getText(
            None,  # 父窗口
            "请手动登陆邮箱,获取一次性密码!",  # 对话框标题
            "请输入一次性密码:",  # 提示文本
        )
    def show_message_box_in_main_thread(self, title, message, email):
        """在主线程中显示确认对话框"""
        try:
            reply = QMessageBox.question(
                self, 
                title,
                message,
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            # 设置响应结果并触发事件
            self.dialog_response = (reply == QMessageBox.StandardButton.Yes)
            self.dialog_event.set()
        except Exception as e:
            self.log(f"显示对话框异常: {str(e)}")
            self.dialog_response = False
            self.dialog_event.set()

    def on_bindaccount_thread(self):
        self.btn_bindAccount.setEnabled(False)
        self.btn_clear.setEnabled(False)
        self.pushButton_StopBind.setEnabled(True)
        Global.G_BindGame.isScriptRun=True
        curGame = Global.G_BindGame
        country_code = Global.read_ini(Global.ConfigFileName, 'System', '国家', 'global')


        def disb_ui():
            self.btn_bindAccount.setEnabled(True)
            self.btn_clear.setEnabled(True)
            self.pushButton_StopBind.setEnabled(False)
        try:
            game = GameFun(self.guestaccount, self.token, proxy_info=self.proxy, country_code=country_code, isBind=True,gamedata=curGame)
            self.log(f"开始登陆账号:{self.username}")
            isSuccess, auto_token = game.account_Login(self.username, self.userpass, country_code)
            if not isSuccess:
                self.log(f"账号登陆失败:{auto_token}")
                disb_ui()
                return
            self.log(f"账号:{self.username} 登陆成功")
            self.log(f"[登陆]->开始登陆游客账号:{self.guestaccount}")
            isSuccess, status_code, guestLoginInfo = game.GuestLogin()
            if isSuccess == False:
                if status_code == 10006:
                    self.log(f"请更新游戏版本")
                    disb_ui()
                    return
                if guestLoginInfo:
                    if 'userSuspendInfoList' in guestLoginInfo['postAuthSession']:
                        suspendType = guestLoginInfo['postAuthSession']['userSuspendInfoList'][0]['suspendType']
                        suspendReasonText = guestLoginInfo['postAuthSession']['userSuspendInfoList'][0]['suspendReasonText']
                        if suspendType > 0:
                            self.log(f"[登陆]->账号已被封禁,错误类型:{suspendType}错误信息:{suspendReasonText}")
                            disb_ui()
                            return
                self.log("[登陆]->失败")
                disb_ui()
                return
            self.log("[登陆]->游戏登陆成功!")
            max_retries = 5
            retry_count = 0
            game.GetUserData()
            # while curGame.isScriptRun and retry_count < max_retries:
            #     userInitialTutorialStepList = curGame.Info["Player"].get('userInitialTutorialStepList', None)
            #     if not userInitialTutorialStepList:
            #         game.tutorial_skip()
            #     userInfoList = curGame.Info["Player"].get('userInfoList', None)
            #     name = ""
            #     if userInfoList:
            #         name = userInfoList[0].get("name", "")
            #     if not name:
            #         playerName = Global.取随机字符串(2, 8, True, True, True, True)
            #         self.log(f"[名称]->确认名称:{playerName}")
            #         if game.CheckUserName(playerName) and game.CreateUser(playerName):
            #             break
            #     else:
            #         break
            #     retry_count += 1
            # else:
            #     self.log("[警告]->确认名称已达最大重试次数")
            #     time.sleep(2)
            #     return

            # 剧情_IDS = [41, 32, 6, 51, 5, 39, 40, 42, 50, 14, 37, 9]
            # for id in 剧情_IDS:
            #     userGeneralTutorialList = curGame.Info["Player"].get('userGeneralTutorialList', None)
            #     if userGeneralTutorialList:
            #         tutorialCompletedBit0 = int(userGeneralTutorialList[0].get('tutorialCompletedBit0', 0))
            #         if self.is_bit_set(tutorialCompletedBit0, id) == False:
            #             self.log(f"[剧情]->跳过剧情,ID:{id}")
            #             if not game.tutorial_complete(id):
            #                 curGame.proxy = None
            #                 continue

            isSuccess, playeid = game.link_status_check(auto_token)
            if playeid:
                self.log("[绑定]->该账号已绑定游戏数据,请更换!")
                disb_ui()
                return
            isSuccess,status_code = game.bind_link()
            if isSuccess:
                self.log("[绑定]->绑定成功!")
            else:
                self.log("[绑定]->绑定失败!")
        except Exception as e:
            self.log(f"绑定账号异常: {str(e)}")
        finally:
            disb_ui()


    def on_bind_account(self):
        self.textEdit_log.setText('')
        self.guestaccount = self.edit_guestAccount.text().strip()  #游客账号
        self.token=self.edit_token.text().strip()   #游客密码
        #self.uuid = self.edit_UUID.text().strip()
        self.username = self.edit_email.text().strip()
        self.userpass =self.edit_emailpass.text().strip()
        #self.Getmail_adress = self.edit_Getmail_adress.text().strip()
        #self.once_pass = self.edit_once_pass.text().strip()
        proxyStr = self.edit_proxyIP.text().strip()
        if proxyStr:
            try:
                self.proxy = ProxyUtil.Parse(proxyStr)
            except Exception as e:
                QMessageBox.warning(self, "异常", f"{e}")
                return

        # 验证输入
        if not self.guestaccount or not self.token or not self.username or not self.userpass:
            QMessageBox.warning(self, "输入错误", "请填写完整的账号信息")
            return

        self.bind_thread = threading.Thread(target=self.on_bindaccount_thread)
        self.bind_thread.start()

    def log(self, message):
        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 格式化日志消息
        log_message = f"[{current_time}] {message}"
        # 添加到日志文本框
        self.textEdit_log.append(log_message)
        
    def on_clear_fields(self):
        # 清空所有编辑框
        self.edit_token.clear()
        self.edit_guestAccount.clear()
        self.edit_UUID.clear()
        self.edit_emailpass.clear()
        self.edit_email.clear()
        self.edit_once_pass.clear()
        self.account=''
        self.username=''

        # 记录日志
        self.log("已清空所有输入框")
    def on_stopBind(self):
        if self.bind_thread is not None:
            Global.G_BindGame.isScriptRun=False
        self.btn_bindAccount.setEnabled(True)
        self.btn_clear.setEnabled(True)
        self.pushButton_StopBind.setEnabled(False)




    def BindProcess(self,id,token,account,password):
        try:
            # gamefun = GameFun(id)
            # isSuccess, guestLoginInfo = gamefun.GuestLogin()
            # if isSuccess == False:
            #     self.log("[登陆]->失败")
            #     time.sleep(5)
            #     return
            # self.log("[登陆]->登陆成功!")
            pass
        except Exception as e:
            Global.LOGE(f"绑定异常{e}")

    def ReadCode(self):
        self.Getmail_adress = self.Getmail_adress.replace("{mail}", self.email).replace("{pass}", self.emailpass)
        http= HttpUtil()
        mail_ret= http.get(self.Getmail_adress)
        print(mail_ret)
        _, _, after_colon = mail_ret.partition("：")
        code = after_colon.split("-----------")[0].strip()
        return code.replace("<br />","")
    def account_Login(self, user, password, country):
        try:
            url = "https://account-api.bandainamcoid.com/v3/login/idpw"
            now = datetime.now()
            cookie_Data = {
                "__ulfpc": now.strftime("%Y%m%d") + str(int(now.timestamp())),
                "language": "zh-cn",
                "OptanonConsent": "isGpcEnabled=0&datestamp=Sat+Apr+19+2025+16:37:10+GMT+0800+(中国标准时间)&version=202505.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&consentId=03fac145-3389-430c-a67c-1ece31dce2de&interactionCount=0&isAnonUser=1&landingPath=https://account.bandainamcoid.com/login.html?client_id=idportal&customize_id=&redirect_uri=https%3A%2F%2Fwww.bandainamcoid.com%2Fv2%2Foauth2%2Fauth%3Fback%3Dv3%26client_id%3Didportal%26scope%3DJpGroupAll%26redirect_uri%3Dhttps%253A%252F%252Fwww.bandainamcoid.com%252F%26text%3D&prompt=&groups=C0004:0,C0003:0,C0002:0,C0001:1",
                "retention_tmp": "1"
            }
            if country == "jp":
                cookie_Data[
                    "OptanonConsent"] = 'isGpcEnabled=0&datestamp=Tue+Apr+22+2025+09:43:43+GMT+0800+(中国标准时间)&version=202505.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&consentId=3f538987-36b2-4924-a811-83e7549fdad2&interactionCount=0&isAnonUser=1&landingPath=https://account.bandainamcoid.com/login.html?client_id=sdgundamgeneration_account_link&redirect_uri=uniwebview://bnid/accept&prompt=login&groups=C0004:0,C0003:0,C0002:0,C0001:1'
            params = {
                'client_id': 'sdgundamgeneration_ww_account_link',
                'redirect_uri': 'uniwebview://bnid/accept',
                'customize_id': '',
                'login_id': user,
                'password': password,
                'retention': '1',
                'language': 'zh-cn',
                'cookie': json.dumps(cookie_Data, ensure_ascii=False),
                'prompt': 'login'
            }
            if country == "jp":
                params["client_id"] = "sdgundamgeneration_account_link"

            body = urlencode(params)
            resp, status_code, erro = self.http_util.post(url, body, proxy=self.proxy)
            data = json.loads(resp)
            if 'result' in data:
                result = data['result']
                if str(result).lower() == "ok":
                    if 'redirect' in data:
                        auth_token = data['redirect'].split('code=')[1].split('"')[0]
                        return True, auth_token
                    elif 'input_error' in data:
                        erro = data['input_error']["other"]
                        return False, erro
                    elif 'redirect_no-cache' in data and (redirect := data[
                        'redirect_no-cache']) and "uniwebview%3A%2F%2Fbnid%2Faccept" in redirect:  # 'https://account.bandainamcoid.com/login.html?client_id=sdgundamgeneration_ww_account_link&redirect_uri=uniwebview%3A%2F%2Fbnid%2Faccept&customize_id='
                        cookie_data = data.get("cookie", {})
                        cookie_dict = {
                            v["name"]: v["value"]
                            for v in cookie_data.values()
                            if "name" in v and "value" in v
                        }

                        return self.account_Agreen(cookie_dict)
                    else:
                        return False, f"未知错误:{resp}"
                else:
                    return False, f"登陆错误:{result}"
            else:
                return False, f"未知错误:{resp}"
        except Exception as e:
            self.log(f"账号登陆异常{e}")
        return False, ""

    def account_Agreen(self, cookie):
        try:
            url = "https://account-api.bandainamcoid.com/v3/login/agree?"
            utc_now = datetime.now(timezone.utc)
            iso_format = utc_now.isoformat(timespec="milliseconds").replace("+00:00", "Z")
            cookie_Data = cookie
            cookie_Data[
                'OptanonConsent'] = f'isGpcEnabled=0&datestamp=Tue Aug 12 2025 13:56:09 GMT+0800 (中国标准时间)&version=202505.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&consentId=5c7ff7e4-9b7d-4229-afed-bf8c90de3591&interactionCount=2&isAnonUser=1&landingPath=NotLandingPage&groups=C0004:0,C0003:0,C0002:0,C0001:1&AwaitingReconsent=false&intType=3&geolocation=TW;TPE'
            cookie_Data['OptanonAlertBoxClosed'] = iso_format
            params = {
                'client_id': 'sdgundamgeneration_ww_account_link',
                'redirect_uri': 'uniwebview://bnid/accept',
                'customize_id': '',
                'language': 'zh-cn',
                'cookie': json.dumps(cookie, ensure_ascii=False),
            }
            body = urlencode(params)
            http = HttpUtil()
            resp = http.get(url + body, proxy=self.proxy)
            print(resp)
            data = json.loads(resp)
            if 'result' in data:
                result = data['result']
                if str(result).lower() == "ok":
                    if 'redirect' in data:
                        auth_token = data['redirect'].split('code=')[1].split('"')[0]
                        return True, auth_token
                    elif 'input_error' in data:
                        erro = data['input_error']["other"]
                        return False, erro
                    else:
                        return False, f"未知错误:{resp}"
                else:
                    return False, f"登陆同意错误:{result}"
            else:
                return False, f"未知错误:{resp}"
        except Exception as e:
            self.log(f"账号同意异常{e}")
        return False, ""